package com.tanhua.dubbo.api;

import com.mongodb.client.result.DeleteResult;
import com.tanhua.model.vo.SoundVo;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

/**
 * @Author: Alan_Zhang
 * @Date: 2022/1/8 - 01 - 08 - 15:37
 * @Description: com.tanhua.dubbo.api
 * @version: 1.0
 */
@DubboService
public class SoundApiImpl implements SoundApi{
    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    public void sendVoice(SoundVo soundVo) {
        mongoTemplate.save(soundVo);
    }

    @Override
    public SoundVo reciveVoice(Long userId,int time) {
//        随机抽取语音,并且排除掉自己发送的语音
        TypedAggregation<SoundVo> aggregation= Aggregation.newAggregation(SoundVo.class,
                Aggregation.sample(1),
                Aggregation.match(Criteria.where("id").nin(userId)));
        AggregationResults<SoundVo> aggregate = mongoTemplate.aggregate(aggregation, SoundVo.class);

        SoundVo result = aggregate.getUniqueMappedResult();
        result.setRemainingTimes(10-time);
        Query query=Query.query(Criteria.where("soundUrl").is(result.getSoundUrl()));
        mongoTemplate.remove(query, SoundVo.class);

        return result;
    }


}
